<?php
function getTree($arr, $pid = 0, $level = 1)
{
    static $list = [];
    foreach ($arr as $key => $value) {
        if ($value["pid"] == $pid) {
            $value["level"] = $level;
            $list[] = $value;
            unset($arr[$key]); //删除已经排好的数据为了减少遍历的次数，当然递归本身就很费神就是了
            getTree($arr, $value["id"], $level + 1);
        }
    }
    return $list;
}


function generateTree($data)
{
    $items = array();
    foreach ($data as $v) {
        $items[$v['id']] = $v;
    }
    $tree = array();
    foreach ($items as $k => $item) {
        if (isset($items[$item['pid']])) {
            $items[$item['pid']]['list'][] = &$items[$k];
        } else {
            $tree[] = &$items[$k];
        }
    }
    return $tree;
}


/**
 * 返回固定格式json
 * @param  string  $msg  提示信息
 * @param  integer $code 返回状态码,0为正常,1位异常
 * @param  [type]  $data 返回数据集
 * @return [type]        
 */
function json($msg = 'ok', $code = 0, $data = null, $count = 0)
{
    $arr["code"] = $code;
    $arr["count"] = $count;
    $arr["msg"]  = $msg;
    $arr["data"] = $data;
    header('Content-Type:application/json; charset=utf-8');
    exit(json_encode($arr));
}


/**
 * 循环删除目录下的所有文件
 * @param  string  $dirName 路径
 */
function deldir($dirName)
{
    if ($handle = opendir("$dirName")) {
        while (false !== ($item = readdir($handle))) {
            if ($item != "." && $item != "..") {
                if (is_dir("$dirName/$item")) {
                    deldir("$dirName/$item");
                } else {
                    if (unlink("$dirName/$item"));
                }
            }
        }
        closedir($handle);
    }
}
